<template>
	<el-card>
		<!-- <el-form :inline="true">
			<el-form-item>
				<el-button v-auth="'sys:org:save'" type="primary" @click="addOrUpdateHandle()">新增</el-button>
			</el-form-item>
		</el-form> -->
		<!-- <add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update> -->
		<Condition v-model:condition="condition" :btns="['search', 'reset']" @search="conditionSearch"
			@reset="conditionReset">
			<el-button v-auth="'sys:org:save'" :icon="Plus" type="primary" @click="add">新增</el-button>
		</Condition>
		<el-table v-loading="loading" :data="List" row-key="id" border style="width: 100%">
			<el-table-column prop="id" label="序号" header-align="center" align="center" width="50">
				<template #default="scope">
					{{ (pagination.page - 1) * pagination.limit + scope.$index + 1 }}
				</template>
			</el-table-column>
			<el-table-column prop="orgCode" label="机构编码" header-align="center" align="center"></el-table-column>
			<el-table-column prop="name" label="机构名称" header-align="center" align="center"></el-table-column>
			<!-- <el-table-column prop="parentName" label="上级" header-align="center" align="center"></el-table-column> -->
			<el-table-column prop="orgTypeName" label="机构类型" header-align="center" align="center"></el-table-column>
			<el-table-column prop="orgLevelName" label="级别等级" header-align="center" align="center"></el-table-column>
			<el-table-column label="行政区划" header-align="center" align="center">
				<template #default="scope">
					<span v-if="scope.row.provName">
						{{ scope.row.provName + scope.row.cityName + scope.row.distName }}
					</span>
				</template>
			</el-table-column>
			<el-table-column prop="sort" label="排序" header-align="center" align="center"></el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center">
				<template #default="scope">
					{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}
				</template>
			</el-table-column>
			<el-table-column prop="status" label="机构状态" header-align="center" align="center">
				<template #default="scope">
					<el-switch :model-value="scope.row.status" @change="switchChange($event, scope.row)" :active-value="1"
						:inactive-value="0" />
					<span style="margin-left: 5px">{{ scope.row.status == '1' ? '正常' : '注销' }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
				<template #default="scope">
					<el-button v-auth="'sys:org:detail'" type="primary" link @click="details(scope.row)">详情</el-button>
					<el-button v-auth="'sys:org:update'" type="primary" link @click="update(scope.row)">编辑</el-button>
					<el-button v-auth="'sys:org:connect'" type="primary" link @click="connect(scope.row)">关联平台</el-button>
					<el-button v-auth="'sys:org:delete'" type="primary" link @click="del(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination :current-page="pagination.page" :page-sizes="pagination.pageSizes" :page-size="pagination.limit"
			:total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChange"
			@current-change="currentChange">
		</el-pagination>
		<el-dialog v-model="dialog.visible" top="50px" :title="dialog.title" :close-on-click-modal="false" draggable>
			<Form ref="modalForm" v-model:formState="formState" :formData="formData"></Form>
			<template v-if="dialog.state !== 'details'" #footer>
				<el-button @click="dialog.visible = false">取消</el-button>
				<el-button type="primary" @click="dialogSave" :loading="dialog.loading">确定</el-button>
			</template>
		</el-dialog>
		<el-dialog v-model="dialog2.visible" :title="dialog2.title" :close-on-click-modal="false" draggable>
			<Form ref="modalForm" v-model:formState="formState2" :formData="formData2"></Form>
			<template #footer>
				<el-button @click="dialog2.visible = false">取消</el-button>
				<el-button type="primary" @click="dialogSave2" :loading="dialog2.loading">确定</el-button>
			</template>
		</el-dialog>
	</el-card>
</template>

<script setup lang="ts" name="SysOrgIndex">
import { Plus } from '@element-plus/icons-vue'
import service from '@/utils/request'
import Condition from '@/components/Condition/index.vue'
import Form from '@/components/Form/index.vue'
// import { useCrud } from '@/hooks'
import { reactive, ref, computed, onMounted } from 'vue'
// import AddOrUpdate from './add-or-update.vue'
// import { IHooksOptions } from '@/hooks/interface'
import { valueReset, valuable, typeOf } from '@/utils/tool'
import { useDictProviceApi, useDictProviceSysApi, useDictTypeAllSysApi } from '@/api/sys/dict'
import { getDelOrgCode } from '@/api/sys/orgs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { throttle } from '@/utils/tool'
import { tr } from 'element-plus/es/locale'
import { parseTime } from '@/utils/tool'

const loading = ref(false)
const pagination = ref({
	page: 1,
	limit: 20,
	total: 0,
	pageSizes: [10, 20, 50, 100, 200]
})

const sizeChange = val => {
	pagination.value = {
		...pagination.value,
		page: 1,
		limit: val
	}
	getList()
}
const currentChange = val => {
	pagination.value = {
		...pagination.value,
		page: val
	}
	getList()
}
const List = ref([])
const condition = ref<P.conditionItem[]>([
	{ dataIndex: 'day', type: 'dayRange', value: ['', ''] },
	{ dataIndex: 'name', type: 'input', value: '', placeholder: '机构名称' },
	{ dataIndex: 'orgTypeCode', type: 'select', value: '', data: [], placeholder: '机构类型' },
	{ dataIndex: 'orgLevelCode', type: 'select', value: '', data: [], placeholder: '级别等级' }
])

const conditionSearch = () => {
	pagination.value.page = 1
	getList()
}

const conditionReset = () => {
	condition.value.map(v => {
		v.value = valueReset(v.value)
	})
	pagination.value.page = 1
	getList()
}

const dialog = ref({
	title: '新增机构',
	type: 'add',
	visible: false,
	loading: false
})

const dialog2 = ref({
	title: '关联平台',
	type: 'update',
	visible: false,
	loading: false
})
const formState2 = ref({
	orgCode: '',
	platformIds: []
})
const platformIds_old = ref([])
const formData2 = ref([
	{
		dataIndex: 'platformIds',
		type: 'tree',
		data: [],
		disabled: false,
		label: 'label'
	}
])
const connect = item => {
	dialog2.value.type = 'update'
	const ids = new Set()
	item.platforms.map(v => {
		ids.add(v.id)
		// ids.add(v.classifyId)
	})
	formState2.value.orgCode = item.orgCode
	formState2.value.platformIds = Array.from(ids)
	platformIds_old.value = Array.from(ids)

	const params = {
		// orgCode: item.id
	}
	service.post('/sys/org/classifyList', params).then(res => {
		formData2.value[0].data = res.data.filter(v => {
			if (v.children?.length) {
				return true
			}
		})
	})

	dialog2.value.visible = true
}
const dialogSave2_before = () => {
	return new Promise((resolve, reject) => {
		const ids = []

		console.log(platformIds_old.value)
		console.log(formState2.value.platformIds)

		const count = platformIds_old.value.reduce((p, c) => {
			if (!formState2.value.platformIds.includes(c)) {
				ids.push(c)
				return p + 1
			} else {
				return p
			}
		}, 0)

		if (count) {
			const params = {
				orgCode: formState2.value.orgCode,
				platformIdLists: ids
			}
			service
				.post('/sys/platform/platformRoleList', params)
				.then(res => {
					if (res.data) {
						ElMessageBox.confirm(
							`系统检测到[${count}个]平台被取消，此操作会影响涉及平台下的[${res.data}]个角色所绑定的用户权限，请谨慎操作`,
							'警告',
							{
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								type: 'warning'
							}
						)
							.then(() => {
								resolve()
							})
							.catch(() => {
								reject()
							})
					} else {
						resolve()
					}
				})
				.catch(e => {
					reject(e.msg)
				})
		} else {
			resolve()
		}
	})
}
const dialogSave2 = async () => {
	try {
		await dialogSave2_before()
		dialog2.value.loading = true
		const params = { ...formState2.value }
		params['platformIds'] = params['platformIds'].filter(v => {
			return typeOf(v) === 'number'
		})

		service
			.post('/sys/orgPlatform/updateRelation', params)
			.then(res => {
				dialog2.value.loading = false
				if (res.code === 0) {
					ElMessage({
						message: '编辑成功!',
						type: 'success'
					})
					dialog2.value.visible = false
					getList()
				} else {
					ElMessage({
						message: res.message,
						type: 'error'
					})
				}
			})
			.catch(e => {
				dialog2.value.loading = false
			})
	} catch (e) {
		dialog2.value.loading = false
		console.log(e)
	}
}
const parent = ref()
const treeChange = e => {
	if (typeOf(e) === 'array') {
		parent.value = {}
		formState.value.pid = ''
	} else {
		parent.value = e
		formState.value.pid = e.id
	}
}

const getdict = (code, type, value, leaf) => {
	return new Promise((resolve, reject) => {
		const params = {
			type: type,
			patientId: value
		}
		// const params = {
		// 	page: 1,
		// 	limit: 1000,
		// 	dictTypeId: code,
		// 	dictType: type,
		// 	patientId: value
		// }
		// let str = ''
		// for (let key in params) {
		// 	if (str) {
		// 		str = str + '&' + key + '=' + params[key]
		// 	} else {
		// 		str = key + '=' + params[key]
		// 	}
		// }

		// useDictByTypeApi(params).then(res => {
		// 	const list = res.data.map(v => {
		// 		return {
		// 			label: v.dictLabel,
		// 			value: v.dictValue,
		// 			leaf: leaf
		// 		}
		// 	})
		// 	resolve(list)
		// })

		useDictTypeAllSysApi(params).then(res => {
			// console.log(res.data.list, 'list')
			// const list = res.data.list.map(v => {
			// 	return {
			// 		label: v.dictLabel,
			// 		value: v.dictValue,
			// 		leaf: leaf
			// 	}
			// })
			const list = res.data.map(v => {
				return {
					label: v.dictLabel,
					value: v.dictValue,
					leaf: leaf
				}
			})
			resolve(list)
		})
	})
}
const getdictArea = (code, type, value, leaf) => {
	return new Promise((resolve, reject) => {
		const params = {
			// type: type,
			pcode: value
		}

		useDictProviceSysApi(params).then((res) => {
			const list = res.data.map(v => {
				return {
					label: v.name,
					value: v.code,
					leaf: leaf
				}
			})
			resolve(list)
		})
	})
}
const levelData2 = ref([])
const levelData3 = ref([])
const provinceLoadData = (node, resolve) => {
	const { value, level } = node
	getdict(51, 'area', value ? value : 0, level >= 2).then(res => {
		resolve(res)
		if (level === 1) {
			levelData2.value = res
		} else if (level === 2) {
			levelData3.value = res
		}
	})
}
const org_type_code_change = (val, reset = true) => {
	if (val) {
		getdict(53, 'hospital_center', val, false).then(res => {
			const item = formData.value.find(v => {
				return v.dataIndex === 'orgChildTypeCode'
			})
			if (res.length) {
				if (reset) {
					formState.value.orgChildTypeCode = ''
				}
				item.data = res
				item.hidden = false
			} else {
				item.data = []
				item.hidden = true
			}
		})
	} else {
		const item = formData.value.find(v => {
			return v.dataIndex === 'orgChildTypeCode'
		})
		if (reset) {
			formState.value.orgChildTypeCode = ''
		}
		item.data = []
		item.hidden = true
	}
}
const getOrgCode = val => {
	getDelOrgCode({ orgCode: String(val) }).then(res => {
		if (res.data) {
			ElMessageBox.confirm(`已新增过该机构，是否重新编辑该机构?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					formState_reset(res.data)
				})
				.catch(() => {
					formState.value.orgCode = ''
				})
		}
	})
}

const switchChange = throttle(async (e, item) => {
	if (!e) {
		await ElMessageBox.confirm(`确定要注销[${item.name}]吗?`, '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				return Promise.resolve()
			})
			.catch(() => {
				return Promise.reject()
			})
	}
	const params = {
		id: item.id,
		pid: item.pid,
		status: e
	}

	service.post('/sys/org/update', params).then(res => {
		if (res.code === 0) {
			ElMessage({
				message: '操作成功',
				type: 'success'
			})
			getList()
		}
	})
}, 500)

onMounted(() => {
	getList()
	getTree()
	let obj = formData.value.reduce((p, c, i) => {
		p[c.dataIndex] = i
		return p
	}, {})
	let obj2 = condition.value.reduce((p, c, i) => {
		p[c.dataIndex] = i
		return p
	}, {})
	getdict(51, 'area', 0, false).then(res => {
		formData.value[obj['province']].data = res
	})
	getdict(52, 'org_center', 0, false).then(res => {
		formData.value[obj['orgTypeCode']].data = res
		condition.value[obj2['orgTypeCode']].data = res
	})
	getdict(55, 'org_level', 0, false).then(res => {
		formData.value[obj['orgLevelCode']].data = res
		condition.value[obj2['orgLevelCode']].data = res
	})
})

const formState = ref({
	pid: '',
	id: '',
	source: 1,
	status: 1,
	isDivide: 0,
	name: '',
	orgCode: '',
	orgTypeCode: '',
	orgChildTypeCode: '',
	orgLevelCode: '',
	adminLevel: '',
	province: '',
	address: '',
	sort: 0
})

const formState_reset = item => {
	modalForm.value && modalForm.value.reset()
	const obj = {
		pid: '',
		id: '',
		source: 1,
		status: 1,
		isDivide: 0,
		name: '',
		orgCode: '',
		orgTypeCode: '',
		orgChildTypeCode: '',
		orgLevelCode: '',
		adminLevel: '',
		province: '',
		address: '',
		sort: 0
	}
	if (item) {
		for (let key in obj) {
			obj[key] = item[key]
		}
		console.log(obj)
		if (item.provCode) {
			obj['province'] = [item.provCode, item.cityCode, item.distCode]
		}
		formState.value = { ...formState.value, ...obj }
	} else {
		formState.value = { ...obj }
	}
}

const formData = ref([
	{
		title: '机构名称',
		dataIndex: 'name',
		type: 'input',
		disabled: false,
		rules: [{ required: true, message: '请输入机构名称', trigger: 'blur' }]
	},
	{
		title: '统一社会信用编码',
		dataIndex: 'orgCode',
		type: 'input',
		disabled: false,
		blur: getOrgCode,
		rules: [{ required: true, message: '请输入统一社会信用编码', trigger: 'blur' }]
	},
	{
		title: '机构来源',
		dataIndex: 'source',
		type: 'select',
		data: [
			{
				label: '线上填写',
				value: 1
			},
			{
				label: '表单导入',
				value: 2
			}
		],
		hidden: true,
		disabled: true
	},
	{
		title: '机构状态',
		dataIndex: 'status',
		type: 'switch',
		active: 1,
		activeText: '已生效',
		inactive: 0,
		inactiveText: '已注销',
		disabled: false
	},
	{
		title: '是否分院',
		dataIndex: 'isDivide',
		type: 'switch',
		active: 1,
		activeText: '是',
		inactive: 0,
		inactiveText: '否',
		disabled: false
	},
	{
		title: '机构类型',
		dataIndex: 'orgTypeCode',
		type: 'select',
		bind: {
			filterable: true
		},
		data: [],
		disabled: false,
		change: org_type_code_change,
		rules: [{ required: true, message: '请选择机构类型', trigger: 'change' }]
	},
	{
		title: '机构分类',
		dataIndex: 'orgChildTypeCode',
		type: 'select',
		bind: {
			filterable: true
		},
		data: [],
		disabled: false,
		hidden: false,
		rules: [{ required: true, message: '请选择机构分类', trigger: 'change' }]
	},
	{
		title: '级别等级',
		dataIndex: 'orgLevelCode',
		type: 'select',
		data: [],
		disabled: false,
		rules: [{ required: true, message: '请选择级别等级', trigger: 'change' }]
	},
	{
		title: '行政级别',
		dataIndex: 'adminLevel',
		type: 'select',
		data: [
			{
				label: '省级',
				value: '省级'
			},
			{
				label: '市级',
				value: '市级'
			},
			{
				label: '县级',
				value: '县级'
			},
			{
				label: '乡镇',
				value: '乡镇'
			},
			{
				label: '其他',
				value: '其他'
			}
		],
		disabled: false,
		rules: [{ required: true, message: '请选择行政级别', trigger: 'change' }]
	},
	{
		title: '排序',
		dataIndex: 'sort',
		type: 'inputNumber',
		disabled: false,
		rules: [{ required: true }]
	},
	{
		title: '行政区划(省市区)',
		dataIndex: 'province',
		type: 'cascader',
		data: [],
		disabled: false,
		loadData: provinceLoadData
	},
	{
		title: '详情地址',
		dataIndex: 'address',
		type: 'textarea',
		disabled: false
	},
	{
		title: '上级机构',
		dataIndex: 'pid',
		type: 'select-tree',
		label: 'name',
		value: 'id',
		data: [],
		onChange: treeChange,
		disabled: false
	}
])
const modalForm = ref()

const formStateReset = item => {
	const obj = {
		orgCode: ''
	}
	if (item) {
		formState.value = { ...obj, ...item }
	} else {
		formState.value = { ...obj }
	}
}
const add = () => {
	dialog.value.state = 'add'
	dialog.value.title = '新增机构'
	formState_reset()
	org_type_code_change('', true)

	formData.value.map(v => {
		if (v.dataIndex === 'source') {
			v.hidden = true
			v.disabled = true
		} else {
			v.disabled = false
		}
	})

	dialog.value.visible = true
}

const update = async item => {
	try {
		dialog.value.state = 'update'
		dialog.value.title = '编辑机构'
		formState_reset(item)

		if (formState.value.pid) {
			parent.value = {
				name: item.parentName
			}
		}

		org_type_code_change(formState.value.orgTypeCode, false)

		if (formState.value.province) {
			const province = formData.value.find(v => {
				return v.dataIndex === 'province'
			})

			const firstItem = province.data.find(v => {
				return v.value === item.provCode
			})

			const second = await getdict(51, 'area', item.provCode, false)

			firstItem['children'] = second
			levelData2.value = second

			const secondItem = second.find(v => {
				return v.value === item.cityCode
			})

			const thrid = await getdict(51, 'area', item.cityCode, true)

			secondItem['children'] = thrid
			levelData3.value = thrid
		}

		formData.value.map(v => {
			if (v.dataIndex === 'source') {
				v.hidden = false
				v.disabled = true
			} else if (v.dataIndex === 'orgCode') {
				v.disabled = true
			} else {
				v.disabled = false
			}
		})
		dialog.value.visible = true
	} catch (e) {
		console.log(e)
	}
}

const del = item => {
	ElMessageBox.confirm(`确定要删除[${item.name}]吗?此操作执行后不可恢复，请谨慎操作!`, '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			service
				.post('/sys/org/delete', {
					id: item.id
				})
				.then(res => {
					if (res.code === 0) {
						ElMessage({
							message: '删除成功!',
							type: 'success'
						})
						getList()
					} else {
						ElMessage({
							message: res.message,
							type: 'error'
						})
					}
				})
		})
		.catch(() => {
			console.log('取消')
		})
}

const details = async item => {
	try {
		dialog.value.state = 'details'
		dialog.value.title = '机构详情'
		formState_reset(item)

		if (formState.value.pid) {
			parent.value = {
				name: item.parentName
			}
		}

		org_type_code_change(formState.value.orgTypeCode, false)

		if (formState.value.province) {
			const province = formData.value.find(v => {
				return v.dataIndex === 'province'
			})

			const firstItem = province.data.find(v => {
				return v.value === item.provCode
			})

			const second = await getdict(51, 'area', item.provCode, false)

			firstItem['children'] = second
			levelData2.value = second

			const secondItem = second.find(v => {
				return v.value === item.cityCode
			})

			const thrid = await getdict(51, 'area', item.cityCode, true)

			secondItem['children'] = thrid
			levelData3.value = thrid
		}

		formData.value.map(v => {
			if (v.dataIndex === 'source') {
				v.hidden = false
				v.disabled = true
			} else {
				v.disabled = true
			}
		})
		dialog.value.visible = true
	} catch (e) {
		console.log(e)
	}
}

const dialogSave = async () => {
	try {
		await modalForm.value.submit()
		dialog.value.loading = true
		const params = { ...formState.value }

		let obj = formData.value.reduce((p, c, i) => {
			p[c.dataIndex] = i
			return p
		}, {})
		if (params.province && params.province[0]) {
			params.provCode = params.province[0]
			const item = formData.value[obj['province']].data.find(v => {
				return v.value === params.province[0]
			})
			params.provName = item.label
			params.cityCode = params.province[1]
			const item2 = levelData2.value.find(v => {
				return v.value === params.province[1]
			})
			params.cityName = item2.label
			params.distCode = params.province[2]
			const item3 = levelData3.value.find(v => {
				return v.value === params.province[2]
			})
			params.distName = item3.label
		}
		if (params.pid === '' || !params.pid) {
			params.pid = 0
		} else {
			params.parentName = parent.value.name
		}
		params.orgTypeName = formData.value[obj['orgTypeCode']].data.find(v => {
			return v.value === formState.value['orgTypeCode']
		})?.label
		params.orgLevelName = formData.value[obj['orgLevelCode']].data.find(v => {
			return v.value === formState.value['orgLevelCode']
		})?.label
		params.orgChildTypeName = formData.value[obj['orgChildTypeCode']].data.find(v => {
			return v.value === formState.value['orgChildTypeCode']
		})?.label
		if (dialog.value.state === 'add') {
			service
				.post('/sys/org', params)
				.then(res => {
					dialog.value.loading = false
					if (res.code === 0) {
						ElMessage({
							message: '新增成功!',
							type: 'success'
						})
						dialog.value.visible = false
						getList()
					} else {
						ElMessage({
							message: res.message,
							type: 'error'
						})
					}
				})
				.catch(e => {
					dialog.value.loading = false
				})
		} else {
			service
				.post('/sys/org/update', params)
				.then(res => {
					dialog.value.loading = false
					if (res.code === 0) {
						ElMessage({
							message: '修改成功!',
							type: 'success'
						})
						dialog.value.visible = false
						getList()
					} else {
						ElMessage({
							message: res.message,
							type: 'error'
						})
					}
				})
				.catch(e => {
					dialog.value.loading = false
				})
		}
	} catch (e) {
		console.log(e)
		dialog.value.loading = false
	}
}

const getTree = () => {
	service.get('/sys/org/list').then(res => {
		if (res.code === 0) {
			const item = formData.value.find(v => {
				return v.dataIndex === 'pid'
			})
			item.data = res.data
		}
	})
}

const getList = () => {
	loading.value = true
	let obj = condition.value.reduce((p, c) => {
		if (valuable(c.value)) {
			if (c.dataIndex === 'day') {
				p['startTime'] = c.value[0]
				p['endTime'] = c.value[1]
			} else {
				p[c.dataIndex] = c.value
			}
		}
		return p
	}, {})
	const { page, limit } = pagination.value
	service
		.get('/sys/org/page', {
			params: { ...obj, page, limit }
		})
		.then(res => {
			loading.value = false
			if (res.code === 0) {
				List.value = res.data.list
				pagination.value.total = res.data.total
			}
		})
		.catch(() => {
			loading.value = false
		})
}

// const state: IHooksOptions = reactive({
// 	dataListUrl: '/sys/org/list',
// 	deleteUrl: '/sys/org',
// 	isPage: false
// })
// const { getDataList, deleteHandle } = useCrud(state)

// const addOrUpdateRef = ref()
// const addOrUpdateHandle = (id?: Number) => {
// 	addOrUpdateRef.value.init(id)
// }
</script>
